// featurePackage/pages/searchResult/searchResult.js

import { querySearchProducts } from "../../../service/jb_home_service"
import debounce from "../../../tools/debounce"
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    layoutType: "one",//两行 one:单行
    goodList: [

    ],

    isBottomShow: false,
    refreshFlag: false,
    isShowLoading: false,
    searchWord: "",
    page: 1,
    limit: 10,
    isPartner: "",//是合伙人商品
    isPersonCustom: "",//是否是私人定制商品
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.searchWord) {
      this.setData({
        searchWord: options.searchWord
      })
    }
    if (options.isPartner) {
      this.setData({
        isPartner: true,
      })
    }
    if (options.isPersonCustom) {
      this.setData({
        isPersonCustom: true,
      })
    }
    this.querySearchProducts('refresh');
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  //搜索变化
  searchBarChange(e) {
    console.log("JJLog:e:" + JSON.stringify(e));
    this.setData({
      searchWord: e.detail
    })
    debounce(this.querySearchProducts('refresh'));
  },

  //列表布局切换
  layoutChangeAction() {
    this.setData({
      layoutType: this.data.layoutType == 'one' ? 'two' : 'one'
    })
  },
  querySearchProducts(type) {
    wx.showLoading();
    // console.log(this.data);
    querySearchProducts(this.data.searchWord, this.data.page, this.data.limit, this.data.isPartner, this.data.isPersonCustom).then(res => {
      wx.hideLoading()
      if (res.code == 200 && res.data) {
        let arr = (type == 'refresh' ? [] : this.data.goodList || []);
        arr = arr.concat(res.data.list || [])
        this.setData({
          goodList: arr,
          refreshFlag: false,
          isShowLoading: false,
          isBottomShow: res.data.totalPage == this.data.page ? true : false,
        })
      }
      console.log("JJLog:搜索结果是:" + JSON.stringify(res));
    }).catch(err => {
      wx.hideLoading()
      console.error("JJLog:querySearchProducts", err);
      wx.showToast({
        title: err || '加载失败',
        icon: "none"
      })
      if (this.data.page != 1) {
        this.setData({
          page: this.data.page - 1
        })
      }
      this.setData({
        refreshFlag: false,
      })
    })
  },




  // 下拉刷新
  handleRefresh() {
    // TODO
    this.setData({
      page: 1,
      isBottomShow: false,
      refreshFlag: true,
      searchWord: '',
    })
    this.querySearchProducts('refresh');
  },
  // 加载更多
  handleLoadmore() {
    console.log('加载更多');
    if (this.data.isBottomShow) {
      return;
    }
    this.setData({
      isShowLoading: true,
      page: this.data.page + 1
    })
    this.querySearchProducts()
  },







  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})